<?php
/**
 * Created by PhpStorm.
 * User: FDG296
 * Date: 2017/8/28
 * Time: 13:48
 *
 * 修改时间：2018/3/1
 * 修改人：lizenan
 * 修改功能：【后台需求】商品查询增加操作日志
 *任务ID：525
 */
namespace backend\controllers;

use backend\models\BuySet;
use backend\models\GoodsRelation;
use backend\models\GoodsSale;
use backend\models\UploadForm;
use Yii;
use yii\web\AdminController;
use backend\models\GoodsCategory;
use backend\models\GoodsBrand;
use backend\models\GoodsListEdit;

class GoodsMatchController extends AdminController{
    public $layout = false;
    //业务关键字
    public $service = 'GoodsMatch';

    //首页
    public function actionIndex(){
        $model = new UploadForm();
        return $this->render('index',['model'=>$model]);
    }

    //获取搭配列表
    public function actionGetMatchList(){
        $data = Yii::$app->request->post();
        $condition = array();
        if(!empty($data['search_set_name'])){
            $condition = ['like','set_name',$data['search_set_name']];
        }
        $query = BuySet::find()->where($condition);
        $count = $query->count();
        $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
        $list = $query->offset($data['start'])->limit($data['length'])
            ->orderBy(array("$sort_string"=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->asArray()->all();
        if(empty($list)){
            $list = array();
        }

        //相关参数   http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }

    //保存数据
    public function actionMatchSave(){
        $model = new BuySet();
        $data = Yii::$app->request->post();
        $data_now['set_name'] = $data['set_name'];
        $data_now['img_main'] = $data['img_main'];
        $data_now['img_main_alt'] = $data['img_main_alt'];
        $data_now['img_small'] = $data['img_small'];
        $data_now['img_small_alt'] = $data['img_small_alt'];
        $data_now['link'] = $data['link'];
        $data_now['sort'] = empty($data['sort']) ? 1 : $data['sort'];
        $data_now['use_flg'] = $data['use_flg'];

        if(empty($data['match_id'])){
            //新增
            $data_now['creator'] = $model->getCreator();
            $data_now['create_time'] = date('Y-m-d H:i:s',time());
            $res = Yii::$app->db->createCommand()->insert('j_buy_set',$data_now)->execute();
        }else{
            //编辑
            $data_now['editor'] = $model->getCreator();
            $data_now['edit_time'] = date('Y-m-d H:i:s',time());
            $res = $model::updateAll($data_now, "id=:id",array(':id'=> $data['match_id']));
        }

        if($res > 0){
            $this->retJson('处理成功',200);
        }else{
            $this->retJson('处理失败',500);
        }
    }

    /**
     * 取得单个搭配信息
     */
    public function actionGetMatchDetail(){
        try{
            $data = Yii::$app->request->post();

            if(empty($data['id'])){
                $this->retJson('参数错误！',9003);
            }
            $result = BuySet::findOne(array('id'=>$data['id']));
            $this->retJson(\yii\helpers\Json::encode($result),200);

        }catch(\Exception $e){
            //add by allen.qiang 20180112 异常处理，日志优化 start
            //error_log($e->getMessage());
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson('系统异常',9003);
        }
    }

    //启用禁用
    public function actionChangeMatchUseflg(){
        $model = new BuySet();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = $data['use_flg'];
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, "id = :id",array('id' => $data['id']));

        if($data['use_flg'] == 1){
            $retMsg = '启用';
        }else{
            $retMsg = '禁用';
        }
        if($res > 0){
            $this->retJson('商品搭配' . $retMsg . '成功',200);
        }else{
            $this->retJson('商品搭配' . $retMsg . '失败',500);
        }
    }

    //搭配商品列表
    public function actionGoodsList(){
        $data = Yii::$app->request->get();
        $title = $id_title = '';
        if ($data['type'] == 1){
            $result = BuySet::findOne(array('id'=>$data['id']));
            $id_title = $result['set_name'];
            $title = '商品搭配商品页';
        }elseif ($data['type'] == 2){
            $result = GoodsCategory::findOne(array('id'=>$data['id']));
            $id_title = $result['category_name'];
            $title = '分类搭配商品页';
        }elseif ($data['type'] == 3){
            $result = GoodsBrand::findOne(array('id'=>$data['id']));
            $id_title = $result['brand_name'];
            $title = '品牌搭配商品页';
        }elseif ($data['type'] == 4){
            $result = GoodsListEdit::findOne(array('id'=>$data['id']));
            $id_title = $result['goods_name_cn'];
            $title = '商品搭配商品页';
        }
        $this->saveLog($this->service,$title,'VIEW','');                     //日志
        return $this->render('goods-list', ['set_id'=> $data['id'],'title'=>$id_title,'type'=>$data['type']]);
    }

    //搭配商品列表
    public function actionGetGoodsList(){
        $data = Yii::$app->request->post();
        $title = $GLOBALS['_GOODS_RELATION_KEY'][$data['type']];
        $data['search_set_id'] = $title . $data['search_set_id'];
        $condition = ['relation_key'=>$data['search_set_id']];
        $query = GoodsRelation::find()->where($condition)->alias('gr');
        $count = $query->count();
        $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
        $list = $query->offset($data['start'])->limit($data['length'])
            ->orderBy(array("$sort_string"=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->asArray()->all();
        if(empty($list)){
            $list = array();
        }

        //相关参数   http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }

    //添加搭配商品
    public function actionSaveMatchGoods(){
        $data = Yii::$app->request->post();
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if(empty($data['sku'])){
                throw new \Exception('提交数据不能为空');
            }
            
            $sku_list = $data['sku'];
            $sort_list = $data['add_sort'];
            
            foreach($sku_list as $value){
                if(empty($value)){
                    throw new \Exception('请删除空数据之后在提交');
                }
            }
            
            if (count($sku_list) != count(array_unique($sku_list))) {
                throw new \Exception('请删除');
            }
            
            $goods_list_where = ['sku'=>$sku_list];
            $goods_list = GoodsSale::find()->where($goods_list_where)->select('sku,main_goods_id,goods_id,goods_name_cn')->asArray()->all();
            $goods_list_sku = array();
            foreach($goods_list as $value){
                $goods_list_sku[$value['sku']] = $value;
            }
            $model = new GoodsRelation();
            $title = $GLOBALS['_GOODS_RELATION_KEY'][$data['set_type']];
            $buy_set_id = $title . $data['set_id'];
            
            //判断物料号
            $buy_set_where = ['relation_key'=>$buy_set_id];
            $buy_set_list = $model::find()->where($buy_set_where)->asArray()->all();
            $set_list = array();
            foreach($buy_set_list as $value){
                $set_list[$value['main_goods_id']] = $value;
            }
            foreach($sku_list as $value){
                if(empty($goods_list_sku[$value])){
                    throw new \Exception('物料号[ '.$value.' ]不存在,请检查或同步数据之后再提交');
                }
                
                if(!empty($set_list[$goods_list_sku[$value]['main_goods_id']])){
                    throw new \Exception('物料号[ '.$value.' ]对应的主商品已经添加,请删除之后再提交');
                }
            }
            
            $list = array();
            foreach($sku_list as $key=>$value){
                $list[] = [$buy_set_id,$goods_list_sku[$value]['main_goods_id'],$goods_list_sku[$value]['goods_id'],
                    $value,$goods_list_sku[$value]['goods_name_cn'],$sort_list[$key],1,$model->getCreator(),date('Y-m-d H:i:s',time())];
            }
            $field_name = ['relation_key','main_goods_id','goods_id','sku','goods_name_cn','sort','use_flg','creator','create_time'];
            $red = Yii::$app->db->createCommand()->batchInsert('j_goods_relation', $field_name, $list)->execute();
            if($red > 0){
                //创建商品搭配商品写入日志
				//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 start
                $goods_list_edit = new GoodsListEdit();
                $goods = $goods_list_edit::find()->select('main_goods_id,goods_id')->where('id=:id',[':id'=>$data['set_id']])->asArray()->one();
                $new_buy_set_list = $model::find()->select('sku,goods_id')->where($buy_set_where)->asArray()->all();
                $goods_list_edit->writeGoodsLog($goods['main_goods_id'],'',9,$new_buy_set_list,$buy_set_list);
                //add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 end
				$transaction->commit();
                $this->retJson('操作成功',200);
            }else{
                throw new \Exception('操作失败');
            }
        } catch (\Exception $e) {
            $this->retJson($e->getMessage(),500);
            $transaction->rollBack();
        }
    }

    //启用禁用
    public function actionChangeRelationUseflg(){
        $model = new GoodsRelation();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = $data['use_flg'];
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, "id = :id",array('id' => $data['id']));

        if($data['use_flg'] == 1){
            $retMsg = '启用';
        }else{
            $retMsg = '禁用';
        }
        if($res > 0){
            $this->retJson('商品搭配' . $retMsg . '成功',200);
        }else{
            $this->retJson('商品搭配' . $retMsg . '失败',500);
        }
    }

    //删除搭配中的商品
    public function actionDelGoodsRelation(){
        $model = new GoodsRelation();
        $goods_list_edit = new GoodsListEdit();
        $data = Yii::$app->request->post();
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $relation_key = $model::findOne($data['id']);
            $res = $model::deleteAll("id = :id",array('id' => $data['id']));
            if($res > 0){
				//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 start
				//删除商品搭配写入日志
                $id = explode('_', $relation_key['relation_key']);
                $goods = $goods_list_edit::findOne($id[1]);
                $goods_list_edit->writeGoodsLog($goods['main_goods_id'],$relation_key['goods_id'],10);
				//add by lizenan 20180301 【后台需求】商品查询增加操作日志 525 end
                $transaction->commit();
                $this->retJson('商品搭配删除成功',200);
            }else{
                throw new \Exception('商品搭配删除失败');
            }
        } catch (\Exception $e) {
            $this->retJson($e->getMessage(),500);
            $transaction->rollBack();
        }
    }

    //编辑搭配商品顺序
    public function actionModGoodsSort(){
        $model = new GoodsRelation();
        $data = Yii::$app->request->post();
        $mod_data['sort'] = $data['sort'];
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, "id = :id",array('id' => $data['update_id']));
        if($res > 0){
            $this->retJson('操作成功',200);
        }else{
            $this->retJson('操作失败',500);
        }
    }
}